package com.sxc.oa.web.action;

import com.sxc.oa.utils.DButil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/user/login")
public class UserServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean success = false;
        //验证用户名和密码是否正确
        //获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //连接数据库验证用户名和密码
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DButil.getConnction();
            String sql = "select * from t_user where username = ? and password = ?";
            //编译sql
            ps= conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);

            rs = ps.executeQuery();
            if (rs.next()) {
                //登陆成功
                success = true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                DButil.close(conn,ps,rs);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(success){
        response.sendRedirect(request.getContextPath()+"/dept/list");
        }else {
response.sendRedirect(request.getContextPath()+"/error.html");
        }

        //登录成功/失败

    }
}
